package com.zzyl.nursing.service.impl;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.ai.AiInvoker;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.HealthReportVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 健康评估Service业务层处理
 * 
 * @author zjx
 * @date 2025-05-20
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 智能评测
     * 
     * @param dto 健康评估
     * @return 结果
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AiInvoker aiInvoker;
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto dto)
    {
        if(StringUtils.isEmpty(dto.getIdCard()) || "null".equals(dto.getIdCard())){
            throw new BaseException("身份证号是不合法的");
        }
        if(StringUtils.isEmpty(dto.getElderName()) || "null".equals(dto.getElderName())){
            throw new BaseException("老人的姓名是不合法的");
        }
        if(StringUtils.isEmpty(dto.getPhysicalExamInstitution()) || "null".equals(dto.getPhysicalExamInstitution())){
            throw new BaseException("体检医院是不合法的");
        }
        if(StringUtils.isEmpty(dto.getPhysicalReportUrl()) || "null".equals(dto.getPhysicalReportUrl())){
            throw new BaseException("url链接是不合法的");
        }
        //1.从redis中获取保存的pdf文本内容
        String pdfText = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_ASSESSMENT_HASH, dto.getIdCard());
        if(StringUtils.isEmpty(pdfText)){
            throw new BaseException("文件上传失败");
        }
        //2.调用AI接口
        InputStream input = this.getClass().getClassLoader().getResourceAsStream("prompt.txt");
        String  read = String.valueOf(IoUtil.read(input));
        String template = read.replace("prompt", pdfText);
        String result = aiInvoker.invoker(template);
        if(StringUtils.isEmpty(result)){
            throw new BaseException("调用AI千帆大模型失败");
        }
        HealthReportVo healthReportVo = JSON.parseObject(result, HealthReportVo.class);

        //3.保存AI分析信息到数据库中
        HealthAssessment healthAs = saveHealthAssessment(dto, healthReportVo);
        redisTemplate.delete(CacheConstants.HEALTH_ASSESSMENT_HASH);
        Long id = healthAs.getId();
        return id;
    }

    private @NotNull HealthAssessment saveHealthAssessment(HealthAssessmentDto dto, HealthReportVo healthReportVo) {
        HealthAssessment healthAs = new HealthAssessment();
        healthAs.setElderName(dto.getElderName());
        healthAs.setIdCard(dto.getIdCard());
        healthAs.setPhysicalExamInstitution(dto.getPhysicalExamInstitution());
        healthAs.setPhysicalReportUrl(dto.getPhysicalReportUrl());
        healthAs.setBirthDate(IDCardUtils.getBirthDateByIdCard(dto.getIdCard()));
        healthAs.setAge(IDCardUtils.getAgeByIdCard(dto.getIdCard()));
        healthAs.setGender(IDCardUtils.getGenderFromIdCard(dto.getIdCard()));
        healthAs.setHealthScore(String.valueOf(healthReportVo.getHealthAssessment().getHealthIndex()));
        healthAs.setTotalCheckDate(healthReportVo.getTotalCheckDate());
        healthAs.setReportSummary(healthReportVo.getSummarize());
        healthAs.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());
        healthAs.setDiseaseRisk(JSON.toJSONString(healthReportVo.getRiskDistribution()));
        healthAs.setAbnormalAnalysis(JSON.toJSONString(healthReportVo.getAbnormalData()));
        healthAs.setSystemScore(JSON.toJSONString(healthReportVo.getSystemScore()));
        healthAs.setSuggestionForAdmission(healthReportVo.getHealthAssessment().getHealthIndex()>60?0:1);
        healthAs.setNursingLevelName(nursingLevel(healthReportVo.getHealthAssessment().getHealthIndex()));
        healthAs.setAdmissionStatus(1);
        healthAs.setAssessmentTime(LocalDateTime.now());
        this.save(healthAs);
        return healthAs;
    }

    private String nursingLevel(double healthIndex) {
        String level = "不建议入住";
        if(healthIndex>=90){
            level="三级护理等级";
        }else if(healthIndex>=80){
            level="二级护理等级";
        }else if(healthIndex>=70){
            level="一级护理等级";
        }else if(healthIndex>=60){
            level="特级护理等级";
        }
        return level;
    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return updateById(healthAssessment) ? 1 : 0;
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
}
